package com.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.apiresult.CommonResult;
import com.common.apiresult.ResultCode;
import com.common.constant.RedisConstant;
import com.common.domain.dto.WaterElectricityQueryDTO;
import com.common.domain.vo.WaterElectricityPageVO;
import com.common.domain.vo.WaterElectricityVO;
import com.common.exception.BusinessException;
import com.common.utils.RedisUtil;
import com.service.serviceInterface.WaterElectricityService;
import com.system.entity.Dorm;
import com.system.entity.WaterElectricity;
import com.system.mapper.DormMapper;
import com.system.mapper.StudentDormMapper;
import com.system.mapper.WaterElectricityMapper;
import com.system.mapper.WorkInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class WaterElectricityServiceImpl extends ServiceImpl<WaterElectricityMapper, WaterElectricity>
        implements WaterElectricityService {
    @Resource
    private StudentDormMapper studentDormMapper;
    @Resource
    private WaterElectricityMapper waterElectricityMapper;
    @Resource
    private WaterElectricityService waterElectricityService;
    @Resource
    private WorkInfoMapper workInfoMapper;
    @Resource
    private DormMapper dormMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public CommonResult selectPage(WaterElectricityQueryDTO dto, long userId) {
        IPage<WaterElectricity> selectPage = null;
        if (StringUtils.isNotBlank(String.valueOf(userId)) && "0".equals(userId)) {
            selectPage = selectList(dto, "0");
        } else {
            String dormId = studentDormMapper.selectDormIdByUserId(userId);
            selectPage = selectList(dto, dormId);
        }
        if (selectPage.getRecords().size() <= 0) {
            return CommonResult.failed(ResultCode.RETURNNULL);
        }
        List<WaterElectricityVO> vos = new ArrayList<>();
        for (WaterElectricity i : selectPage.getRecords()) {
            WaterElectricityVO vo = new WaterElectricityVO();
            BeanUtils.copyProperties(i, vo);
            vo.setAddName(workInfoMapper.selectNameByUserId(i.getAddUserId()));
            if (!Objects.isNull(i.getModifyTime())) {
                vo.setModifyTime(i.getModifyTime()).setModifyName(workInfoMapper.selectNameByUserId(i.getModifyUserId()));
            }
            vos.add(vo);
        }
        WaterElectricityPageVO pageVO = new WaterElectricityPageVO();
        pageVO.setVo(vos).setTotal(selectPage.getTotal());
        return CommonResult.success(pageVO);
    }

    @Override
    public CommonResult delete(String id) {
        if (id.contains(",")) {
            String[] strings = id.split(",");
            List<String> collect = Arrays.stream(strings).collect(Collectors.toList());
            return waterElectricityService.removeByIds(collect) ? CommonResult.success() : CommonResult.failed();
        }
        return waterElectricityService.removeById(id) ? CommonResult.success() : CommonResult.failed();
    }

    public IPage<WaterElectricity> selectList(WaterElectricityQueryDTO dto, String dormId) {
        String date1 = "";
        String date2 = "";
        SimpleDateFormat endlishFormat = new SimpleDateFormat("EEE MMM dd yyyy hh:mm:ss", Locale.ENGLISH);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM", Locale.CHINA);
        if (dto.getDateRange() != null && dto.getDateRange().get(0) != null && !"".equals(dto.getDateRange().get(0))) {
            String formatDate1 = dto.getDateRange().get(0).replace("GMT", "").replaceAll("\\(.*\\)", "");
            try {
                date1 = dateFormat.format(endlishFormat.parse(formatDate1));
            } catch (ParseException e) {
                throw new BusinessException(ResultCode.VALIDATE_FAILED);
            }
            log.warn("==>" + date1);
        }
        if (dto.getDateRange() != null && dto.getDateRange().get(1) != null && !"".equals(dto.getDateRange().get(1))) {
            String formDate2 = dto.getDateRange().get(1).replace("GMT", "").replaceAll("\\(.*\\)", "");
            try {
                date2 = dateFormat.format(endlishFormat.parse(formDate2));
            } catch (ParseException e) {
                throw new BusinessException(ResultCode.VALIDATE_FAILED);
            }
            log.warn("==>" + date2);
        }
        Page<WaterElectricity> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        return waterElectricityMapper.selectPage(page, addCondition(date1, date2, dormId, String.valueOf(dto.getBuildId())));
    }

    public LambdaQueryWrapper<WaterElectricity> addCondition(String date1, String date2, String dormId, String buildId) {
        LambdaQueryWrapper<WaterElectricity> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(date1) && StringUtils.isNotBlank(date2)) {
            wrapper.between(WaterElectricity::getTime, date1, date2);
        }
        if (StringUtils.isNotBlank(dormId) && !"0".equals(dormId)) {
            wrapper.eq(WaterElectricity::getDormId, dormId);
        }
        if ("0".equals(dormId) && StringUtils.isNotBlank(buildId)) {
            log.error("buildId=" + buildId);
            if (!redisUtil.hasKey(RedisConstant.DORM_LIST)) {
                List dormList = dormMapper.selectList(null);
                redisUtil.setList(RedisConstant.DORM_LIST, dormList, 604800);
            }
            List list = redisUtil.getList(RedisConstant.DORM_LIST);
            List<Long> dorms = new ArrayList<>();
            list.forEach(i -> {
                Dorm dorm = new Dorm();
                BeanUtils.copyProperties(i, dorm);
                dorms.add(dorm.getId());
            });
            wrapper.in(WaterElectricity::getDormId, dorms);
        }
        wrapper.orderByAsc(WaterElectricity::getTime);
        return wrapper;
    }
}




